/**
 * Created by chenxq on 2017/12/25.
 */
/**
 * Created by chenxq on 2017/12/22.
 */
import React,{PureComponent} from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Table, Card, Button ,Form ,Input ,Row ,Col ,Select ,Popconfirm ,Modal ,message ,Divider,DatePicker,Radio,Dropdown,Menu,Icon} from 'antd';
import styles from '../../routes/TableList.less';
import {listParams,payTypes,signStatus} from '../../routes/defaultData';
import {findObjByKey ,convertLongToString} from '../../utils/index';
import AccountList from '../Sign/AccountList';
import {reg} from '../../utils/CheckList';
import AddAccount from '../Sign/AddAccount';
import {Link} from 'dva/router'
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const { Option } = Select;
const {RangePicker} = DatePicker;
@connect(state=>({
  sign:state.sign,
  userManage:state.usermanagement,
  customer:state.customer,
  product:state.product
}))
@Form.create()
export default class extends PureComponent{
  state={
    isvisible:false,
    editObj:{},
    key:Math.random(),
    addAccountIsvisible:false,
    accountListIsvisible:false,
    addKey:Math.random(),
    AddObj:{
      info:{},
      type:'income'
    },
    listIsvisible:false,
    listKey:Math.random(),
    loanId:0
  }
  defaultData={}
  columns=[{
    title:'产品',
    dataIndex:'productId',
    render:(productId)=>{
      let proList=this.props.product.allList || [];
      let obj=proList.find(item=>item.id==productId) || {};
      return obj.name || '';
    }
  },{
    title:'支付方式',
    dataIndex:'payWay',
    render(payWay){
      return payWay? findObjByKey(payTypes,payWay).name :''
    }
  },{
    title:'状态',
    dataIndex:'state',
    render(state){
      return state? findObjByKey(signStatus,state).name :''
    }
  },{
    title:'指派人',
    dataIndex:'assignedTo',
    render:(id)=>{
      let userList=this.props.userManage.allList || [];
      if(!id){
        return '';
      }
      let user=userList.find(item=>item.id==id) || {};
      return user.userName;
    }
  },{
    title:'批复额度',
    dataIndex:'replyQuotas',
    render(val){
      return ((val || 0)/100).toFixed(2)
    }
  },{
    title:'批复利息',
    dataIndex:'replyInterest',
    render(val){
      return ((val || 0)/100).toFixed(2)
    }
  },{
    title:'批复周期',
    dataIndex:'replyPeriod'
  },{
    title: '创建时间',
    dataIndex: 'createdTime',
    render:(createdTime)=>{
      return createdTime? convertLongToString(createdTime) : '';

    }
  },{
    title: "",
    dataIndex: "id",
    render: (id,record) =>{
      //return  //this.gethandle(record);

      return (<div className="operations">
       <Link to={`/sign/detail/${record.id}`}>详情</Link>
        <Divider type="vertical" />
        <Popconfirm title="确定要删除该签单" onConfirm={this.remove.bind(this,record.id)}>
          <a>删除</a>
        </Popconfirm>
      </div>)
    }
  }];

  gethandle=(record={})=>{
    let _this=this;
    const menu = (
      <Menu>
        <Menu.Item>
          <a onClick={this.addAccount.bind(this,record,'income')}>新建收入</a>
        </Menu.Item>
        <Menu.Item>
          <a onClick={this.addAccount.bind(this,record,'cost')}>新建支出</a>
        </Menu.Item>
        <Menu.Item>
          <a onClick={this.showAccount.bind(this,record)}>收支列表</a>
        </Menu.Item>
        <Menu.Item>
          <a onClick={this.showDetail.bind(this,record)}>编辑</a>
        </Menu.Item>
        <Menu.Item>
          <Popconfirm title="确定要删除该签单" onConfirm={this.remove.bind(this,record.id)}>
            <a>删除</a>
          </Popconfirm>
        </Menu.Item>
      </Menu>
    );
    return (<Dropdown overlay={menu}>
      <a className="ant-dropdown-link" >
        操作<Icon type="down" />
      </a>
    </Dropdown>)
  }

  showDetail=(params)=>{
    if(this.props.userManage.allList.length<=0){
      message.error('请先添加用户');
      return ;
    }
    if(this.props.product.allList.length<=0){
      message.error('请先添加产品');
      return ;
    }
    //this.props.form.setFieldsValue(params);
    this.setState({
      editObj:{...params},
      isvisible:true,
      key:Math.random()
    })

  }
  showAccount=(record)=>{
    this.setState({
      listIsvisible:true,
      listKey:Math.random(),
      loanId:record.id
    })

  }

  addAccount=(record,type)=>{
    this.setState({
      AddObj:{
        info:{
          loanId:record.id
        },
        type
      },
      addAccountIsvisible:true,
      addKey:Math.random()
    })
  }

  remove=(id)=>{
    let _this=this;
    this.props.dispatch({
      type:'sign/fetchRemove',
      payload:id
    }).then(jsonData=>{
      if(jsonData.result){
        message.success('删除成功',0.8,()=>{
          _this.getList();
        })
      }else{
        message.error(jsonData.msg);
      }
    })
  }
  submit=()=>{
    let _this=this;
    let {customer} = this.props;
    let {curInfo} = customer ;
    this.props.form.validateFieldsAndScroll((err,values)=>{
      if(!err){
        let params={
          ...values
        };
        params.customerId=curInfo.id;
        if(params.replyQuotas){
          params.replyQuotas=params.replyQuotas *100
        }
        if(params.replyInterest){
          params.replyInterest=params.replyInterest *100
        }
        if(params.cost){
          params.cost=params.cost *100
        }
        if(params.downpayment){
          params.downpayment=params.downpayment *100
        }
        if(params.creditInvestigationFee){
          params.creditInvestigationFee=params.creditInvestigationFee *100
        }
        if(params.infoFee){
          params.infoFee=params.infoFee *100
        }
        if(params.investigateFee){
          params.investigateFee=params.investigateFee *100
        }
        if(params.contractualFee){
          params.contractualFee=params.contractualFee *100
        }
        if(params.additionalFee){
          params.additionalFee=params.additionalFee *100
        }
        if(params.rebateAmount){
          params.rebateAmount=params.rebateAmount *100
        }
        if(params.receivable){
          params.receivable=params.receivable *100
        }
        if(params.netReceipt){
          params.netReceipt=params.netReceipt *100
        }
        let editObj=Object.assign({},this.state.editObj,params);
        let patchType='sign/fetchAdd';
        if(editObj.id){
          patchType='sign/fetchEdit'
        }
        this.props.dispatch({
          type:patchType,
          payload:editObj
        }).then(jsonData=>{
          if(jsonData.result){
            message.success(`${editObj.id?'修改':'添加'}成功`,0.8,()=>{
              _this.handleCancel();
              _this.getList();
              _this.props.dispatch({
                type:'customer/fetchCustomerDetail',
                payload:customer.id
              })
            })
          }else{
            message.error(jsonData.msg)
          }
        });
      }
    })

  }
  handleCancel=()=>{
    this.setState({
      isvisible:false
    })
  }


  getList=()=>{
    let {customer} = this.props;
    let {curInfo} = customer ;
    this.props.dispatch({
      type:'sign/querySignListById',
      payload:curInfo.id
    })
  }


  getFormCell=()=>{
    let {editObj} = this.state;
    let {product,userManage} = this.props;
    let userList=userManage.allList || [];
    let assignList=userManage.assignList || []; // 指派人
    let userIdArr=userList.map(item=>item.id);
    let handleValidator= function(rule,val,callback){
      if(!val){
        callback();
        return;
      }
      if(userIdArr.indexOf(val)>=0){
        callback();
      }else{
        callback('用户不存在')
      }
    };

    return [{
      label:'产品',
      key:'productId',
      component: <Select>
        {product.allList.map(item=>(<Option key={item.id} value={item.id}>{item.name}</Option>))}
      </Select>,
      field:{
        initialValue: editObj.productId || (product.allList[0] ? product.allList[0].id : null),
        rules:[{required:true,message:'请选择产品'}]},
      text:''
    },{
      label:'批复额度',
      key:'replyQuotas',
      component: <Input placeholder="请输入批复额度" />,
      field:{
        initialValue: editObj.replyQuotas && (editObj.replyQuotas /100).toFixed(2) || '',
        rules:[{required:true,message:'请输入批复额度'},
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'批复利息',
      key:'replyInterest',
      component: <Input placeholder="请输入批复利息" />,
      field:{
        initialValue: editObj.replyInterest && (editObj.replyInterest /100).toFixed(2) || '',
        rules:[{required:true,message:'请输入批复利息'},
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'批复周期',
      key:'replyPeriod',
      component: <Input placeholder="请输入批复周期" />,
      field:{
        rules:[{required:true,message:'请输入批复周期'}]
      }
    },{
      label:'支付方式',
      key:'payWay',
      component: <Select>
        {payTypes.map(item=>(<Option key={item.key} value={item.key}>{item.name}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.payWay || payTypes[0].key,
      }
    },{
      label:'当前状态',
      key:'state',
      component: <Select>
        {signStatus.map(item=>(<Option key={item.key} value={item.key}>{item.name}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.state || signStatus[0].key,
      }
    },{
      label:'指派给',
      key:'assignedTo',
      component: <Select mode="combobox"
                         placeholder="请选择"
                         optionFilterProp="children"
                         optionLabelProp="children">
        {assignList.map(item=>(<Option key={item.id} value={item.id}>{item.userName}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.assignedTo,
        rules:[{
          validator: handleValidator
        }]
      }
    },{
      label:'产品成本',
      key:'cost',
      component: <Input placeholder="请输入产品成本" />,
      field:{
        initialValue: editObj.cost && (editObj.cost /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'定金',
      key:'downpayment',
      component: <Input placeholder="请输入定金" />,
      field:{
        initialValue: editObj.downpayment && (editObj.downpayment /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'征信费',
      key:'creditInvestigationFee',
      component: <Input placeholder="请输入征信费" />,
      field:{
        initialValue: editObj.creditInvestigationFee && (editObj.creditInvestigationFee /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'资料费',
      key:'infoFee',
      component: <Input placeholder="请输入资料费" />,
      field:{
        initialValue: editObj.infoFee && (editObj.infoFee /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'调查费',
      key:'investigateFee',
      component: <Input placeholder="请输入调查费" />,
      field:{
        initialValue: editObj.investigateFee && (editObj.investigateFee /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'合同约定费',
      key:'contractualFee',
      component: <Input placeholder="请输入合同约定费" />,
      field:{
        initialValue: editObj.contractualFee && (editObj.contractualFee /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'加收费用',
      key:'additionalFee',
      component: <Input placeholder="请输入加收费用" />,
      field:{
        initialValue: editObj.additionalFee && (editObj.additionalFee /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'是否押还款期数',
      key:'holdRepayment',
      component: <RadioGroup>
        <Radio value={false}>否</Radio>
        <Radio value={true}>是</Radio>
      </RadioGroup>,
      field:{
        initialValue: !!editObj.holdRepayment
      }
    },{
      label:'是否有返点',
      key:'rebate',
      component:<RadioGroup>
        <Radio value={false}>否</Radio>
        <Radio value={true}>是</Radio>
      </RadioGroup>,
      field:{
        initialValue: !!editObj.rebate
      }
    },{
      label:'返点金额',
      key:'rebateAmount',
      component: <Input placeholder="请输入返点金额" />,
      field:{
        initialValue: editObj.rebateAmount && (editObj.rebateAmount /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'应收总费用',
      key:'receivable',
      component: <Input placeholder="请输入应收总费用" />,
      field:{
        initialValue: editObj.receivable && (editObj.receivable /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'实收总费用',
      key:'netReceipt',
      component: <Input placeholder="请输入实收总费用" />,
      field:{
        initialValue: editObj.netReceipt && (editObj.netReceipt /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'备注',
      key:'remark',
      span:24,
      formItemLayout : {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      },
      component: <Input.TextArea  placeholder="请输入备注"  />
    },{
      label:'客户经理',
      key:'customerManager',
      component: <Select mode="combobox"
                         placeholder="请选择"
                         optionFilterProp="children"
                         optionLabelProp="children"
      >
        {userList.map((item,index)=>(<Option key={item.id} value={item.id}>{item.userName}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.customerManager,
        rules:[{
          validator: handleValidator
        }]
      }
    },{
      label:'权证经理',
      key:'warrantManager',
      component: <Select mode="combobox"
                         placeholder="请选择"
                         optionFilterProp="children"
                         optionLabelProp="children">
        {userList.map(item=>(<Option key={item.id} value={item.id}>{item.userName}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.warrantManager,
        rules:[{
          validator: handleValidator
        }]
      }
    },{
      label:'贷款经理',
      key:'loanManager',
      component: <Select mode="combobox"
                         placeholder="请选择"
                         optionFilterProp="children"
                         optionLabelProp="children">
        {userList.map(item=>(<Option key={item.id} value={item.id}>{item.userName}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.loanManager,
        rules:[{
          validator: handleValidator
        }]
      }
    },{
      label:'经手人',
      key:'brokerage',
      component: <Select mode="combobox"
                         placeholder="请选择"
                         optionFilterProp="children"
                         optionLabelProp="children">
        {userList.map(item=>(<Option key={item.id} value={item.id}>{item.userName}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.brokerage,
        rules:[{
          validator: handleValidator
        }]
      }
    },{
      label:'复合人',
      key:'reviewPerson',
      component: <Select mode="combobox"
                         placeholder="请选择"
                         optionFilterProp="children"
                         optionLabelProp="children">
        {userList.map(item=>(<Option key={item.id} value={item.id}>{item.userName}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.reviewPerson,
        rules:[{
          validator: handleValidator
        }]
      }
    }]

  }

  componentDidMount(){
    this.getList();
    this.props.dispatch({
      type:'usermanagement/fetchAllList',
      payload:{}
    });
    this.props.dispatch({
      type:'usermanagement/fetchAssignList',
      paylaod:{}
    })
    this.props.dispatch({
      type:'product/fetchAllList',
      payload:'USING'
    })
  }
  render(){
    let {editObj} = this.state;
    let {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };

    return (<Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>
          </div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={this.showDetail.bind(this,this.defaultData)}>
              创建签单
            </Button>
          </div>
          <div style={{marginTop: "20px"}}>
            <Table rowKey="id"
                   loading={this.props.sign.loading}
                   columns={this.columns}
                   pagination={{...this.state.pagination,total:this.props.sign.total}}
                   dataSource={this.props.sign.allList}
                   onChange={this.getList}
            />
          </div>
        </div>
      <Modal title={editObj.id ? "编辑签单":"创建签单"}
             onOk={this.submit}
             onCancel={this.handleCancel}
             visible={this.state.isvisible}
             width={750}
             key={this.state.key}
      >
        <Form className={styles.modal}>
          <Row gutter={24}>
            {this.getFormCell().map((item,index)=>{
              return <Col span={item.span || 12} key={item.key}>
                <FormItem label={item.label} {...(item.formItemLayout || formItemLayout)} validateFirst={true}>
                  {getFieldDecorator(item.key,{
                    initialValue:editObj[item.key] || '',
                    ...item.field
                  })(
                    item.component
                  )}
                </FormItem>
              </Col>
            })}
          </Row>
        </Form>

      </Modal>
      <AddAccount isvisible={this.state.addAccountIsvisible}
                  key={this.state.addKey}
                  {...this.state.AddObj}
                  onCancel={()=>{
                    this.setState({
                      addAccountIsvisible:false
                    })
                  }}

      ></AddAccount>
      <Modal title="支出列表"
             footer={null}
             width={1200}
             key={this.state.listKey}
             visible={this.state.listIsvisible}
             onCancel={()=>{
               this.setState({
                 listIsvisible:false
               })
             }}
      >
        <AccountList type={2} loanId={this.state.loanId}/>
      </Modal>
      </Card>)
  }
}
